//
//  TopicListViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/12/10.
//  Copyright © 2020 王洋. All rights reserved.
//
#import "TopicListCell.h"

#import "TopicListHeaderView.h"
#import "TopicListSectionHeader.h"

#import "BA_CommunityInputTextView.h"
#import "TopicPublishViewController.h"
#import "TopicDetailViewController.h"
#import "TopicListViewController.h"

@interface TopicListViewController ()<UITableViewDelegate, UITableViewDataSource, BA_BottomInputViewDelegate, UITextViewDelegate>

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) TopicListHeaderView *headerView;
@property (nonatomic, strong) ProClassificationModel*headModel;


@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, strong) NSMutableArray <CommonPostModel*>* dataArray;

@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) BA_CommunityInputTextView *footView;

@property (nonatomic, strong) UIButton *addBtn;
@property (nonatomic, copy) NSString * remark;

@end

@implementation TopicListViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    UIWindow * keyWindow = [UIApplication sharedApplication].keyWindow;
    [keyWindow addSubview:self.footView];
    [self.footView hideView];
    
    [self initView];
    
    self.remark = @"2";
    [self refreshParam];
    [self request_topicList];
    [self request_catData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
    [[IQKeyboardManager sharedManager] setEnable:NO];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
    [[IQKeyboardManager sharedManager] setEnable:YES];

    [self.footView hideView];
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    
    [self.footView hideView];
}

-(BOOL)textViewShouldEndEditing:(UITextView *)textView {
    
    [self.footView hideView];
    return YES;
}

-(void)BA_BottomInputViewSendTextMessage:(NSString *)message {
    
    [self request_postEvaWithIndex:self.selectIndex AndContent:message];
}

- (void)refreshParam {
    self.pageSize = 10;
    self.pageNum = 1;
}

- (void)initView {

    self.view.backgroundColor = UIColorHex(0xf5f5f5);
    [self.view addSubview:self.tableview];
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
    
    [self.view addSubview:self.addBtn];
    [self.addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-100);
        make.right.mas_equalTo(-5);
        make.height.width.mas_equalTo(68);
    }];
    
    [self initViewAction];
}

- (void)initViewAction {
    
    WEAKSELF
    self.headerView.TopicListHeaderViewBlock = ^(TopicListHeaderActionType type) {
      
        switch (type) {
            case TopicListHeaderActionType_hot:{
                weakSelf.remark = @"2";
                [weakSelf refreshParam];
                [weakSelf request_topicList];
            } break;
            case TopicListHeaderActionType_new:{
                weakSelf.remark = @"3";
                [weakSelf refreshParam];
                [weakSelf request_topicList];
            } break;
            default:
                break;
        }
    };
}

- (void)addPostAction {
    
    TopicPublishViewController *vc = [[TopicPublishViewController alloc] init];
    ProClassificationModel *model = [[ProClassificationModel alloc] init];
    model.scId = self.headModel.scId;
    model.parentName = self.headModel.parentName;
    vc.model = model;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView.contentOffset.y>100) {
        self.title = self.headModel.parentName;
    }else{
        self.title = @"";
    }
}
    
#pragma mark UITableviewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 90 + 40 + 10;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
//    if (self.dataArray.count >2) {
        return CGFLOAT_MIN;
//    } else {
//        return TTScreenWidth;
//    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    TopicListSectionHeader *sectionHeader = [[NSBundle mainBundle] loadNibNamed:@"TopicListSectionHeader" owner:nil options:nil].firstObject;
    
    [sectionHeader fillWithModel:self.dataArray[section]];
    
    WEAKSELF
    sectionHeader.TopicListSectionHeaderBlock = ^(TopicSectionHeaderActionType type) {
      
        switch (type) {
            case CommunityActionType_Eva:{
                
                weakSelf.selectIndex = section;
                [weakSelf.footView showView];
                [weakSelf.footView.textView becomeFirstResponder];
                
            } break;
            case CommunityActionType_Thumb:{
                
                weakSelf.selectIndex = section;
                [weakSelf request_postThumbWithIndex:section];
                
            } break;
                
            default:
                break;
        }
        
    };
    
    [sectionHeader addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {
        TopicDetailViewController *vc = [[TopicDetailViewController alloc] init];
        vc.pid = weakSelf.dataArray[section].pid;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    }];
    
    return sectionHeader;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footer = [UIView new];
    footer.backgroundColor = UIColor.whiteColor;
    return [UIView new];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    TopicListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TopicListCellID"];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (BA_CommunityInputTextView *)footView {
    if (_footView == nil) {
        _footView = [[BA_CommunityInputTextView alloc]init];
        _footView.delegate = self;
        _footView.textView.delegate = self;
    }
    return _footView;
}

- (UIButton *)addBtn {
    if (!_addBtn) {
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addBtn setImage:[UIImage imageNamed:@"add_post"] forState:UIControlStateNormal];
        [_addBtn addTarget:self action:@selector(addPostAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addBtn;
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.backgroundColor =  UIColorHex(0xf5f5f5);
        
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"TopicListCell" bundle:nil] forCellReuseIdentifier:@"TopicListCellID"];
        
        WEAKSELF
        _tableview.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
            [weakSelf refreshParam];
            [weakSelf request_topicList];
        }];

        _tableview.mj_footer = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            weakSelf.pageNum ++;
            [weakSelf request_topicList];
        }];
        
        _tableview.mj_footer.ignoredScrollViewContentInsetBottom = Is_IPhoneX ? Bottom_SafeHeight : CGFLOAT_MIN;
    }
    return _tableview;
}
    
- (TopicListHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[NSBundle mainBundle] loadNibNamed:@"TopicListHeaderView" owner:nil options:nil].firstObject;
    }
    return _headerView;
}

- (void)request_topicList {
        
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSMutableDictionary *t = @{}.mutableCopy;

    [dic setValue:@(self.pageNum) forKey:@"pageNum"];
    [dic setValue:@(self.pageSize) forKey:@"pageSize"];
    
    [t setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];
    [t setValue:@(self.scId) forKey:@"themeId"];
    [t setValue:@"2" forKey:@"isDel"];
    [t setValue:@"2" forKey:@"type"];
    [t setValue:@"3" forKey:@"status"];
    [t setValue:self.remark forKey:@"remark"];
    [dic setValue:t forKey:@"t"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_SysPosts];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在加载"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSDictionary *resultDic = [data valueForKey:@"data"];
                
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    NSArray *list = [resultDic valueForKey:@"list"];
                    
                    if ([list isKindOfClass:[NSArray class]]) {
                        
                        if (weakSelf.pageNum == 1) {
                            weakSelf.dataArray = @[].mutableCopy;
                        }
                            
                        for (NSDictionary *dic in list) {
                            CommonPostModel *model = [CommonPostModel modelWithDictionary:dic];
                            model.textHeight = [Utilities getStringHeightWithText:model.content font:[UIFont systemFontOfSize:14] viewWidth:(TTScreenWidth - 54)];
                            [weakSelf.dataArray addObject:model];
                        }
                        
                        [self.tableview reloadData];
                        
                    } else {
                        
                    }
                }
            }
        }

    } FailedBlock:^(NSError * _Nonnull error) {

        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
    }];
}


- (void)request_catData {
    
    NSMutableDictionary *dic = @{}.mutableCopy;

    [dic setValue:@"4" forKey:@"scType"];
    [dic setValue:@(self.scId) forKey:@"scId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CurrentCategory];
    
    [SVProgressHUD showWithStatus:@"正在加载"];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                NSArray *resultArr = [data valueForKey:@"data"];
                if ([resultArr isKindOfClass:[NSArray class]]) {

                    if (resultArr.count > 0) {
                        
                        NSDictionary *dic = resultArr[0];
                        weakSelf.headModel = [ProClassificationModel modelWithDictionary:dic];
                        
                        [weakSelf.headerView fillWithModel:weakSelf.headModel];
//                        weakSelf.title = [NSString stringWithFormat:@"#%@#",weakSelf.headModel.parentName];
                        weakSelf.headerView.frame = CGRectMake(0, 0, TTScreenWidth, [TopicListHeaderView calculateHeightWithModel:self.headModel]);
                        weakSelf.tableview.tableHeaderView = self.headerView;
                        weakSelf.headerView.autoresizingMask = UIViewAutoresizingNone;
                    }
                }
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        [SVProgressHUD dismiss];
    }];
}

- (void)request_postEvaWithIndex:(NSInteger)index AndContent:(NSString *)content {
        
    CommonPostModel *model = self.dataArray[index];
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:content forKey:@"content"];

    [dic setValue:model.pid forKey:@"baseId"];
    [dic setValue:@"2" forKey:@"level"];
    [dic setValue:model.source forKey:@"source"];
    [dic setValue:model.userId forKey:@"userId"];
    
    //操作类型（1：评论，2：点赞，3：删除，4：下架，5：取消点赞）必传
    [dic setValue:@"1" forKey:@"mold"];

    //类型（1：谈婚，2：论嫁，3：问答）必传
    [dic setValue:@"2" forKey:@"type"];
    //层级（1,2,3）必传
    [dic setValue:@"2" forKey:@"replySource"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CommonEva];
    
    WEAKSELF
    [SVProgressHUD showWithStatus:@"正在发布评论"];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        [SVProgressHUD dismiss];
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                weakSelf.footView.textView.text = @"";
                [weakSelf.view endEditing:YES];
                
                [weakSelf request_topicList];
                
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
    }];
}


- (void)request_postThumbWithIndex:(NSInteger)index {
        
    CommonPostModel *model = self.dataArray[index];

    NSMutableDictionary *dic = @{}.mutableCopy;

    //点赞帖子
    [dic setValue:model.pid forKey:@"baseId"];
    [dic setValue:@"1" forKey:@"level"];
    [dic setValue:model.source forKey:@"source"];
    [dic setValue:model.userId forKey:@"userId"];

    
    //操作类型（1：评论，2：点赞，3：删除，4：下架，5：取消点赞）必传
    if (model.isZan.length > 0) {
        [dic setValue:@"5" forKey:@"mold"];
        [dic setValue:model.isZan forKey:@"otherId"];
    } else {
        [dic setValue:@"2" forKey:@"mold"];
    }

    //类型（1：谈婚，2：论嫁，3：问答）必传
    [dic setValue:@"2" forKey:@"type"];
    //层级（1,2,3）必传
    [dic setValue:@"2" forKey:@"replySource"];
    [dic setValue:[TTUserModel sharedObject].userId forKey:@"replyUserId"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,API_CommonEva];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        [[TTNoResultManager shareManager] hideNoResultWithView:weakSelf.tableview];
        
        if ([data isKindOfClass:[NSDictionary class]]) {

            //请求成功
            NSInteger code = [[data valueForKey:@"code"] integerValue];
            if (code == 10000) {
                
                NSString *isZan = [data valueForKey:@"data"];
                if ([isZan isKindOfClass:[NSString class]]) {
                    
                    model.isZan = isZan;
                    if (isZan.length > 0) {
                        model.likes++;
                    } else {
                        model.likes--;
                    }
                    
                    [weakSelf.tableview reloadData];
                }
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"message"]];
                [SVProgressHUD dismissWithDelay:1];
            }
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {

    }];
}

@end
